<template>
  <div class="dialogclass">
    <!-- custom-class="dialogclass" -->
    <el-dialog
      v-model="model['isShow']"
      :close-on-click-modal="false"
      destroy-on-close
      title="地图标记"
      width="1100px"
      top="5vh"
    >
      <div class="flex head-but">
        <el-button @click="popClick('hist')">历史记录</el-button>
        <el-button @click="allClear">清空地图所有标记</el-button>
      </div>
      <!-- 操作项 -->
      <div class="main flex">
        <div class="main-left">
          <img
            ref="imageRef"
            class="left-img"
            src="https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg"
            @click="imgClick"
            @load="handleImageLoad"
          />
          <div
            v-for="(item, index) in formData"
            :key="index"
            @click="setNameItem(item, index)"
          >
            <div
              v-if="item.markerPosition.show"
              ref="markerBoxRef"
              class="marker-wrapper"
              :style="{
                left: item.markerPosition.x + 'px',
                top: item.markerPosition.y + 'px',
                width: 'auto'
              }"
            >
              <!-- 图形箭头 -->
              <img
                v-if="item.icon"
                ref="iconRef"
                :src="item.icon"
                class="marker-icon"
              />
              <!-- 图标名称 -->
              <div ref="markerBoxRef" class="marker-box">
                {{ item.name }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="isPosInShow" class="main-right">
          <div class="mark-title">
            {{
              posIn === -1 ? "新增" : !formData[posIn].code ? "新增" : "修改"
            }}标记
          </div>
          <el-form
            :model="currentMarker"
            :rules="rules"
            label-width="auto"
            status-icon
            scroll-to-error
            style="max-width: 600px"
            label-position="top"
          >
            <el-form-item label="标记序号">
              {{
                !formData[posIn]?.code ? formData.length : formData[posIn]?.code
              }}
            </el-form-item>
            <el-form-item label="标记图形">
              <div class="img-list flex">
                <div v-for="(icon, index) in iconList" :key="index">
                  <img :src="icon" alt="" @click="selectIcon(icon)" />
                </div>
              </div>
            </el-form-item>
            <el-form-item label="标记名称">
              <el-input
                v-model="formData[posIn].name"
                maxlength="6"
                @input="setChange"
              />
            </el-form-item>
            <el-form-item label="标记文本">
              <el-button @click="popClick('rich')">请输入标记内容</el-button>
            </el-form-item>
            <el-form-item label="地图跳转">
              <el-input
                v-model="formData[posIn].jump"
                placeholder="请输入地图编号"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">保存</el-button>
              <el-button>删除</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
  <!-- 历史记录弹窗 -->
  <HistPop v-model="isHistPop" />
  <!-- 标记内容的富文本 -->
  <RichTextPop v-model="isRichText" @textChange="textChange" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import HistPop from "./historyPop.vue";
import RichTextPop from "./richTextPop.vue";

const isHistPop = reactive<any>({ isShow: false });
const isRichText = reactive<any>({ isShow: false });
const model = defineModel({ default: { isShow: false, isEdit: false } });
const iconList = [
  new URL("../../../assets/xxx.gif", import.meta.url).href,
  new URL("../../../assets/aaa.gif", import.meta.url).href
  // ... 其他图标路径
];
const formData = ref([]);
const posIn = ref(-1); //-1为新增，其余索引值为修改
const imageRef = ref<HTMLImageElement | null>(null);
const markerBoxRef = ref<HTMLImageElement | null>(null);
const iconRef = ref<HTMLImageElement | null>(null);
const imageSize = reactive({
  width: 0,
  height: 0
});
const rules = reactive<any>([]);
// const markerPosition = reactive({
//   show: false,
//   x: 0,
//   y: 0
// });
// 添加计算属性
const currentMarker = computed(() => formData[posIn.value]);
const isPosInShow = computed(() => posIn.value >= 0);
// -----------------------------onMounted--------------------------
onMounted(() => {
  formData.value = [
    {
      markerPosition: {
        show: true,
        x: 550,
        y: 287
      },
      code: "2",
      icon: "http://localhost:8848/src/assets/aaa.gif",
      jump: "xxx",
      name: "我是1",
      text: '<p><span style="color: rgb(225, 60, 57);"><u>asdadads</u></span></p>'
    },
    {
      markerPosition: {
        show: true,
        x: 230,
        y: 187
      },
      code: "1",
      icon: "http://localhost:8848/src/assets/aaa.gif",
      jump: "xxx",
      name: "aaaaa啊",
      text: '<p><span style="color: rgb(225, 60, 57);"><u>asdadads</u></span></p>'
    }
  ];
});
// -----------------------------method------------------------------
const popClick = e => {
  e === "hist" ? (isHistPop["isShow"] = true) : (isRichText["isShow"] = true);
};
const handleImageLoad = () => {
  if (imageRef.value) {
    imageSize.width = imageRef.value.naturalWidth;
    imageSize.height = imageRef.value.naturalHeight;
    console.log("图片原始尺寸：", imageSize);
  }
};
const imgClick = event => {
  //
  const { offsetX, offsetY } = event;
  // 图片的宽高
  const currentWidth = imageRef.value?.offsetWidth || 0;
  const currentHeight = imageRef.value?.offsetHeight || 0;
  // 鼠标点击的宽高

  // 如果是新增
  if (posIn.value === -1) {
    formData.value.push({
      markerPosition: {
        show: false,
        x: 0,
        y: 0
      },
      code: "",
      icon: "",
      jump: "",
      name: "",
      text: ""
    });
    posIn.value = formData.value.length - 1;
  }
  console.log(
    "%c [  ]-183",
    "font-size:13px; background:pink; color:#bf2c9f;",
    formData.value,
    posIn.value
  );
  const { markerPosition } = formData.value[posIn.value];
  markerPosition.x = offsetX;
  markerPosition.y = offsetY;
  markerPosition.show = true;

  nextTick(() => {
    let iconWidth = iconRef.value ? 40 : 0;
    // 宽高超出边界的设置
    if (offsetY + 28 >= currentHeight) {
      markerPosition.y = currentHeight - 28 - iconWidth;
    }
    let boxWidth = markerBoxRef.value?.offsetWidth;
    if (offsetX + boxWidth >= currentWidth) {
      markerPosition.x = currentWidth - boxWidth;
    }
  });
};
const setChange = () => {
  nextTick(() => {
    const { markerPosition } = formData.value[posIn.value];
    // 获取当前图片宽度
    const currentWidth = imageRef.value?.offsetWidth || 0;
    if (markerBoxRef.value && markerPosition.show) {
      const boxWidth = markerBoxRef.value.offsetWidth;
      // 如果标记盒子超出图片右边界，调整位置
      if (markerPosition.x + boxWidth > currentWidth) {
        markerPosition.x = currentWidth - boxWidth;
      }
    }
  });
  // markerBoxRef.value["offsetWidth"] = 60;
};

const selectIcon = (iconPath: string) => {
  formData.value[posIn.value].icon = iconPath;

  // 如果标记盒子已显示，需要重新调整位置
  // nextTick(() => {
  // if (markerBoxRef.value && formData[0].markerPosition.show) {
  //   const currentWidth = imageRef.value?.offsetWidth || 0;
  //   const boxWidth = markerBoxRef.value.offsetWidth;
  //   const iconWidth = 40; // 图标宽度
  //   const gapWidth = 4; // 间距宽度
  //   // 如果当前位置会导致图标超出左边界
  //   if (formData[0].markerPosition.x < iconWidth + gapWidth) {
  //     formData[0].markerPosition.x = iconWidth + gapWidth;
  //   } else if (formData[0].markerPosition.x + boxWidth > currentWidth) {
  //     formData[0].markerPosition.x = currentWidth - boxWidth;
  //   }
  // }
  // });
};
const textChange = data => {
  isRichText["isShow"] = false;
  formData.value[posIn.value].text = data;
};
const setNameItem = (item, index) => {
  // 点击显示右侧详情
  posIn.value = index;
  console.log(
    "%c [  ]-233",
    "font-size:13px; background:pink; color:#bf2c9f;",
    posIn.value,
    item
  );
};
const allClear = () => {
  ElMessageBox.confirm("确认清空所有标记?", "请确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      formData.value = [];
      posIn.value = -1;
      ElMessage({
        type: "success",
        message: "已全部清空"
      });
    })
    .catch(() => {});
};
// --------------------------
const onSubmit = () => {
  const { show, x, y } = formData.value[posIn.value].markerPosition;
  if (!show)
    return ElMessage({
      type: "error",
      message: "请确定标记位置"
    });
  // formData.value[0]["x"] = x;
  // formData.value[0]["y"] = y;
  console.log(
    "%c [  ]-203",
    "font-size:13px; background:red; color:#bf2c9f;",
    formData
  );
};
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
}
.head-but {
  margin-bottom: 20px;
  justify-content: space-between;
}
.dialogclass {
  ::v-deep(.el-dialog) {
    height: 740px !important;
  }
}
.main {
}
.main-left {
  position: relative;
  .left-img {
    width: 100%;
    height: 620px;
  }
  .marker-wrapper {
    position: absolute;
    display: flex;
    align-items: center;
    gap: 4px;
    // pointer-events: none;
    .marker-icon {
      width: 40px;
      height: 28px; //图标的高度要和名称一致
      object-fit: contain;
    }
    .marker-box {
      position: relative;
      min-width: 40px;
      max-width: 100px;
      height: 28px;
      padding: 0 8px;
      line-height: 28px;
      border-radius: 10px;
      text-align: center;
      color: #ccc;
      font-weight: 600;
      z-index: 999;
      cursor: pointer;
      background-color: #8b3030;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
.main-right {
  flex: 0 0 220px;
  margin-left: 20px;
  padding: 0 10px;
  border-left: 1px solid #ccc;
}
.mark-title {
  margin-bottom: 8px;
  font-weight: 600;
  font-size: 18px;
}
.img-list {
  width: 180px;
  height: 150px;
  border: 1px solid;
  flex-wrap: wrap;
  justify-content: space-around;
  > div {
    width: 40px;
  }
}
</style>
